import React, { useState } from 'react';
import styles from './index.less';
import { useSetState } from 'ahooks';
import moment from 'moment';
import _ from 'lodash';
// components
import { TRMessage } from '#/components/index.js';
import { DeviationPower, DeviationIndex, PredictiveEvaluationRanking, Header } from './components';
import type {
  IProps,
  IOrginDealElementOptions,
  IStationsDataType,
  IFormValue,
  IDealElementOptions,
  IDeviationDataType,
} from '../type';
// api
import { HttpCode } from '#/utils/contacts.js';
import { postDeviationData } from '../services.js';

export default (props: IProps) => {
  const { power } = props;
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [isError, setIsError] = useState<boolean>(false);
  const [provinceOptions, setProvinceOptions] = useState<IDealElementOptions[]>([]); // 省份数据
  const [allStationData, setAllStationData] = useSetState<IStationsDataType>({
    dealElementOptions: [],
    dealElementModalOptions: [],
  }); // 交易单元列表
  const [formValue, setFormValue] = useSetState<IFormValue>({});
  const [dataSource, setDataSource] = useState<IDeviationDataType>();

  React.useEffect(() => {
    defaultRequest();
  }, []);

  // 搜索数据
  const onSearch = async (params: IFormValue) => {
    if (isLoading) {
      TRMessage.info('数据请求中......');
    } else {
      setIsLoading(true);
      const _params: IFormValue = {
        dateStart: params?.dateStart,
        dateEnd: params?.dateEnd,
        stationId: params?.stationId ? Number(params?.stationId) : '',
      };
      setFormValue(params);
      const res = await postDeviationData(_params);
      if (res && res.statusCode === HttpCode.SUCCESS) {
        setDataSource(res?.data);
        setIsError(false);
      } else {
        setIsError(true);
        TRMessage.error(res?.message || '系统异常');
      }
      setIsLoading(false);
    }
  };
  const defaultRequest = async () => {
    const diff = moment().startOf('days').diff(moment().startOf('M').startOf('days'), 'days');
    const temp = power?.[0];
    const stationOptions: any = _.flatten(temp?.children?.map((t: any) => t.children));
    const _power = power.map((t: any) => ({
      ...t,
      children: _.flatten(t.children?.map((t: any) => t.children)),
    }));
    const _params: IFormValue = {
      dateStart:
        diff <= 1 && diff >= 0
          ? moment().subtract(1, 'M').startOf('M').format('YYYY-MM-DD')
          : moment().startOf('M').format('YYYY-MM-DD'),
      dateEnd:
        diff <= 1 && diff >= 0
          ? moment().subtract(1, 'M').endOf('M').format('YYYY-MM-DD')
          : moment().format('YYYY-MM-DD'),
      marketId: temp?.marketId,
      provinceId: temp?.provinceId,
      stationId: stationOptions[0]?.value,
    };
    setAllStationData({
      dealElementOptions: stationOptions,
      dealElementModalOptions: power,
    });

    setProvinceOptions(_power);
    onSearch(_params);
  };

  // 改变省份
  const onChangeProvince = (params: IFormValue, children: any) => {
    setAllStationData({
      dealElementOptions: children,
    });
    setFormValue(params);
  };

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <div className={styles.header}>
          <Header
            values={formValue}
            defaultRequest={defaultRequest}
            provinceOptions={provinceOptions}
            dealElementOptions={allStationData?.dealElementOptions}
            onSearch={onSearch}
            onChangeProvince={onChangeProvince}
          />
        </div>
        <div className={styles.main}>
          <div className={styles.left}>
            <div className={styles.deviationIndex}>
              <DeviationIndex loading={isLoading} error={isError} data={dataSource} />
            </div>
            <div className={styles.deviationPower}>
              <DeviationPower loading={isLoading} error={isError} data={dataSource} />
            </div>
          </div>
          <div className={styles.right}>
            <PredictiveEvaluationRanking loading={isLoading} error={isError} data={dataSource} />
          </div>
        </div>
      </div>
    </div>
  );
};
